/**
 * 增强的LangChain服务 - IntelliMark版
 * 整合新的LangChain实现与现有服务
 */

import { BaseMessage, HumanMessage, SystemMessage } from '@langchain/core/messages'
import Store from 'electron-store'
import { config } from 'dotenv'
import {
  AIProvider,
  AIProviderManager,
  ProviderConfig,
  AIRequestOptions,
  AIStreamOptions
} from './AIProviderAdapter'
import { getTokenManager } from './TokenManager'
import { CacheManager, getAICache } from './CacheManager'
import { getSecurityService } from './SecurityService'
import { log } from '../utils/Logger'

// 导入新的LangChain实现
import {
  initializeAIWriter,
  createWritingAgent,
  generateText,
  analyzeText,
  getLangChainManager
} from '../langchain-implementation/src/index'
import {
  TextGenerationTool,
  TextAnalysisTool,
  MemoryManagementTool,
  ProjectManagementTool
} from '../langchain-implementation/src/tools'
import { getEnhancedAIProviderManager } from '../langchain-implementation/src/utils/aiProviderAdapter'

// Load environment variables
config()

// 扩展的AI操作接口
export interface EnhancedAIAction {
  // 原有功能
  polish: (text: string, options?: any) => Promise<string>
  shorten: (text: string, options?: any) => Promise<string>
  expand: (text: string, options?: any) => Promise<string>
  translate: (text: string, targetLang: string, options?: any) => Promise<string>
  fixGrammar: (text: string, options?: any) => Promise<string>
  changeTone: (text: string, tone: string, options?: any) => Promise<string>
  summarize: (text: string, options?: any) => Promise<string>
  continueWriting: (text: string, context: string, options?: any) => Promise<string>

  // 新增功能
  generateContent: (prompt: string, options?: ContentGenerationOptions) => Promise<string>
  analyzeText: (text: string, analysisType: string, options?: any) => Promise<any>
  formatMarkdown: (text: string) => Promise<string>
  extractKeywords: (text: string) => Promise<string[]>
  generateOutline: (topic: string, options?: OutlineOptions) => Promise<string>
  improveSEO: (text: string) => Promise<string>
}

// 内容生成选项
export interface ContentGenerationOptions {
  style?: 'formal' | 'casual' | 'academic' | 'creative' | 'technical'
  tone?: 'neutral' | 'positive' | 'negative' | 'persuasive' | 'informative'
  length?: 'short' | 'medium' | 'long'
  targetWords?: number
  language?: string
}

// 大纲生成选项
export interface OutlineOptions {
  documentType?: 'essay' | 'report' | 'article' | 'book' | 'tutorial'
  targetAudience?: string
  depth?: 'brief' | 'detailed' | 'comprehensive'
  includeSections?: string[]
}

// 增强的LangChain配置
export interface EnhancedLangChainConfig {
  provider: AIProvider
  apiKey?: string
  model?: string
  temperature?: number
  maxTokens?: number
  baseURL?: string
  timeout?: number
  retries?: number

  // 新增配置
  enableAdvancedFeatures?: boolean
  enableMemoryManagement?: boolean
  enableProjectManagement?: boolean
  enableCaching?: boolean
  enableAnalytics?: boolean
}

export class EnhancedLangChainService implements EnhancedAIAction {
  private config: EnhancedLangChainConfig
  private store: Store
  private providerManager: AIProviderManager
  private tokenManager = getTokenManager()
  private cache = getAICache()
  private securityService = getSecurityService()

  // 新的工具实例
  private textGenerationTool: TextGenerationTool
  private textAnalysisTool: TextAnalysisTool
  private memoryTool: MemoryManagementTool
  private projectTool: ProjectManagementTool

  private isInitialized = false
  private langChainInitialized = false

  constructor() {
    this.store = new Store()
    this.config = this.loadConfig()
    this.providerManager = new AIProviderManager()

    // 初始化新工具
    this.textGenerationTool = new TextGenerationTool({
      defaultProvider: this.getModelId(),
      maxTokens: this.config.maxTokens || 4000,
      temperature: this.config.temperature || 0.7,
    })

    this.textAnalysisTool = new TextAnalysisTool({
      defaultProvider: this.getModelId(),
      maxTokens: this.config.maxTokens || 4000,
      temperature: 0.3, // 分析需要较低温度
    })

    this.memoryTool = new MemoryManagementTool({
      maxEntries: 1000,
      maxAge: 30,
      importanceThreshold: 0.3,
    })

    this.projectTool = new ProjectManagementTool({
      storagePath: './intellimark-projects',
      enableBackups: true,
    })

    this.initialize()
  }

  private loadConfig(): EnhancedLangChainConfig {
    // Load from environment variables first, then fallback to store
    const envConfig: Partial<EnhancedLangChainConfig> = {
      provider: (process.env.AI_PROVIDER || this.store.get('ai.provider', 'openai')) as AIProvider,
      apiKey: process.env.OPENAI_API_KEY || process.env.ANTHROPIC_API_KEY || process.env.DEEPSEEK_API_KEY || this.store.get('ai.apiKey') as string,
      model: process.env.AI_MODEL || this.store.get('ai.model') as string,
      temperature: parseFloat(process.env.AI_TEMPERATURE || String(this.store.get('ai.temperature', 0.7))),
      maxTokens: parseInt(process.env.AI_MAX_TOKENS || String(this.store.get('ai.maxTokens', 4000))),
      baseURL: process.env.AI_BASE_URL || this.store.get('ai.baseURL') as string,
      timeout: parseInt(process.env.AI_TIMEOUT || String(this.store.get('ai.timeout', 60000))),
      retries: parseInt(process.env.AI_RETRIES || String(this.store.get('ai.retries', 3))),

      // 新功能配置
      enableAdvancedFeatures: process.env.ENABLE_ADVANCED_AI !== 'false',
      enableMemoryManagement: process.env.ENABLE_MEMORY !== 'false',
      enableProjectManagement: process.env.ENABLE_PROJECTS !== 'false',
      enableCaching: process.env.ENABLE_AI_CACHE !== 'false',
      enableAnalytics: process.env.ENABLE_AI_ANALYTICS !== 'false',
    }

    return {
      provider: 'openai',
      apiKey: '',
      model: '',
      temperature: 0.7,
      maxTokens: 4000,
      enableAdvancedFeatures: true,
      enableMemoryManagement: true,
      enableProjectManagement: true,
      enableCaching: true,
      enableAnalytics: true,
      ...envConfig
    }
  }

  private async initialize(): Promise<void> {
    if (this.isInitialized) return

    try {
      // Try to load API key from secure storage
      if (!this.config.apiKey) {
        this.config.apiKey = await this.getSecureApiKey() || ''
      }

      await this.initializeProviders()

      // 初始化新的LangChain实现
      if (this.config.enableAdvancedFeatures) {
        await this.initializeAdvancedFeatures()
      }

      this.isInitialized = true
      log.ai(`Enhanced LangChainService initialized with provider: ${this.config.provider}`)
    } catch (error) {
      log.error('Failed to initialize Enhanced LangChainService:', error, 'AI')
      throw error
    }
  }

  private async initializeAdvancedFeatures(): Promise<void> {
    if (!this.langChainInitialized) {
      try {
        await initializeAIWriter({
          provider: this.config.provider,
          apiKey: this.config.apiKey,
          model: this.config.model,
        })
        this.langChainInitialized = true
        log.ai('Advanced LangChain features initialized')
      } catch (error) {
        log.warn('Failed to initialize advanced LangChain features:', error)
      }
    }
  }

  private async initializeProviders(): Promise<void> {
    const { provider, apiKey, model, temperature, maxTokens, baseURL, timeout, retries } = this.config

    if (!apiKey && provider !== 'local') {
      console.warn(`${provider} API key not configured`)
      return
    }

    const providerConfig: ProviderConfig = {
      apiKey: apiKey || '',
      model: model || this.getDefaultModel(provider),
      temperature: temperature || 0.7,
      maxTokens: maxTokens || 4000,
      baseURL,
      timeout: timeout || 60000,
      retries: retries || 3,
    }

    // Import adapter classes
    const {
      OpenAIProviderAdapter,
      AnthropicProviderAdapter,
      DeepSeekProviderAdapter,
      LocalProviderAdapter,
      LongCatProviderAdapter
    } = await import('./AIProviderAdapter')

    switch (provider) {
      case 'openai':
        this.providerManager.registerProvider(provider, new OpenAIProviderAdapter(providerConfig))
        break

      case 'anthropic':
        this.providerManager.registerProvider(provider, new AnthropicProviderAdapter(providerConfig))
        break

      case 'deepseek':
        this.providerManager.registerProvider(provider, new DeepSeekProviderAdapter(providerConfig))
        break

      case 'local':
        if (!baseURL) {
          console.warn('Local models require baseURL configuration (e.g., http://localhost:11434)')
          return
        }
        this.providerManager.registerProvider(provider, new LocalProviderAdapter(providerConfig))
        break

      case 'longcat':
        this.providerManager.registerProvider(provider, new LongCatProviderAdapter(providerConfig))
        break

      default:
        throw new Error(`Unsupported AI provider: ${provider}`)
    }

    this.providerManager.setDefaultProvider(provider)
    console.log(`Initialized ${provider} provider with model: ${providerConfig.model}`)
  }

  private getDefaultModel(provider: AIProvider): string {
    const defaultModels: Record<AIProvider, string> = {
      'openai': 'gpt-4',
      'anthropic': 'claude-3-5-sonnet-20241022',
      'deepseek': 'deepseek-chat',
      'local': 'llama2',
      'longcat': 'LongCat-Flash-Chat'
    }
    return defaultModels[provider]
  }

  private getModelId(): string {
    return `${this.config.provider}-${this.config.model || this.getDefaultModel(this.config.provider)}`
  }

  async updateConfig(newConfig: Partial<EnhancedLangChainConfig>): Promise<void> {
    this.config = { ...this.config, ...newConfig }

    // Save to store
    Object.entries(newConfig).forEach(([key, value]) => {
      this.store.set(`ai.${key}`, value)
    })

    // Reinitialize everything with new config
    this.isInitialized = false
    await this.initialize()
  }

  // 内存管理功能
  public async storeMemory(type: string, content: string, metadata?: any): Promise<void> {
    if (!this.config.enableMemoryManagement) return

    try {
      this.memoryTool.execute({
        action: 'store',
        data: {
          type,
          content,
          metadata,
          importance: 0.7,
          tags: [type],
        }
      })
    } catch (error) {
      log.error('Failed to store memory:', error)
    }
  }

  public async searchMemory(query: string, limit: number = 10): Promise<any[]> {
    if (!this.config.enableMemoryManagement) return []

    try {
      const result = await this.memoryTool.execute({
        action: 'search',
        query,
        options: { limit }
      })
      return result.data || []
    } catch (error) {
      log.error('Failed to search memory:', error)
      return []
    }
  }

  // 原有功能的增强版本
  async polish(text: string, options: any = {}): Promise<string> {
    if (this.config.enableAdvancedFeatures) {
      try {
        const result = await this.textGenerationTool.execute({
          operation: 'polish',
          text,
          style: options.style,
          tone: options.tone,
        })
        return result.data
      } catch (error) {
        log.warn('Advanced polish failed, falling back to basic method:', error)
      }
    }

    return this.executeAction('polish', { text })
  }

  async expand(text: string, options: any = {}): Promise<string> {
    if (this.config.enableAdvancedFeatures) {
      try {
        const result = await this.textGenerationTool.execute({
          operation: 'expand',
          text,
          targetLength: options.targetLength,
          context: options.context,
        })
        return result.data
      } catch (error) {
        log.warn('Advanced expand failed, falling back to basic method:', error)
      }
    }

    return this.executeAction('expand', { text })
  }

  async translate(text: string, targetLang: string = 'English', options: any = {}): Promise<string> {
    if (this.config.enableAdvancedFeatures) {
      try {
        const result = await this.textGenerationTool.execute({
          operation: 'translate',
          text,
          targetLanguage: targetLang,
          language: options.sourceLanguage || 'zh-CN',
        })
        return result.data
      } catch (error) {
        log.warn('Advanced translate failed, falling back to basic method:', error)
      }
    }

    return this.executeAction('translate', { text, target_lang: targetLang })
  }

  async summarize(text: string, options: any = {}): Promise<string> {
    if (this.config.enableAdvancedFeatures) {
      try {
        const result = await this.textGenerationTool.execute({
          operation: 'summarize',
          text,
          targetLength: options.targetLength || 200,
        })
        return result.data
      } catch (error) {
        log.warn('Advanced summarize failed, falling back to basic method:', error)
      }
    }

    return this.executeAction('summarize', { text })
  }

  async continueWriting(text: string, context: string = '', options: any = {}): Promise<string> {
    if (this.config.enableAdvancedFeatures) {
      try {
        const result = await this.textGenerationTool.execute({
          operation: 'continue',
          text,
          context,
          targetLength: options.targetLength,
        })
        return result.data
      } catch (error) {
        log.warn('Advanced continueWriting failed, falling back to basic method:', error)
      }
    }

    return this.executeAction('continueWriting', { text, context })
  }

  // 新增的高级功能
  async generateContent(prompt: string, options: ContentGenerationOptions = {}): Promise<string> {
    if (!this.config.enableAdvancedFeatures) {
      return this.executeAction('generate', { text: prompt })
    }

    try {
      const result = await this.textGenerationTool.execute({
        operation: 'generate',
        prompt,
        style: options.style,
        tone: options.tone,
        length: options.length,
        targetLength: options.targetWords,
      })
      return result.data
    } catch (error) {
      log.error('Content generation failed:', error)
      throw error
    }
  }

  async analyzeText(text: string, analysisType: string, options: any = {}): Promise<any> {
    if (!this.config.enableAdvancedFeatures) {
      return { summary: 'Advanced analysis not available', score: 5 }
    }

    try {
      const result = await this.textAnalysisTool.execute({
        text,
        analysisType: analysisType as any,
        options,
      })
      return result.data
    } catch (error) {
      log.error('Text analysis failed:', error)
      throw error
    }
  }

  async formatMarkdown(text: string): Promise<string> {
    if (!this.config.enableAdvancedFeatures) {
      return text // 基础版本不做处理
    }

    try {
      const result = await this.textGenerationTool.execute({
        operation: 'format',
        text,
      })
      return result.data
    } catch (error) {
      log.error('Markdown formatting failed:', error)
      return text
    }
  }

  async extractKeywords(text: string): Promise<string[]> {
    if (!this.config.enableAdvancedFeatures) {
      return text.split(/\s+/).slice(0, 10) // 简单分词
    }

    try {
      const result = await this.textAnalysisTool.execute({
        text,
        analysisType: 'keywords',
      })
      return result.data?.keywords || []
    } catch (error) {
      log.error('Keyword extraction failed:', error)
      return []
    }
  }

  async generateOutline(topic: string, options: OutlineOptions = {}): Promise<string> {
    if (!this.config.enableAdvancedFeatures) {
      return `# ${topic}\n\n## Introduction\n\n## Main Points\n\n## Conclusion\n\n`
    }

    try {
      const result = await this.textGenerationTool.execute({
        operation: 'outline',
        prompt: topic,
        style: options.documentType as any,
        context: JSON.stringify(options),
      })
      return result.data
    } catch (error) {
      log.error('Outline generation failed:', error)
      throw error
    }
  }

  async improveSEO(text: string): Promise<string> {
    if (!this.config.enableAdvancedFeatures) {
      return text
    }

    try {
      const analysis = await this.textAnalysisTool.execute({
        text,
        analysisType: 'seo',
      })

      if (analysis.data?.suggestions?.length > 0) {
        // 可以根据SEO建议改进文本
        log.info('SEO analysis completed', { suggestions: analysis.data.suggestions })
      }

      return text
    } catch (error) {
      log.error('SEO improvement failed:', error)
      return text
    }
  }

  // 保持与原有接口的兼容性
  async shorten(text: string, options: any = {}): Promise<string> {
    return this.summarize(text, { ...options, targetLength: text.length * 0.3 })
  }

  async fixGrammar(text: string, options: any = {}): Promise<string> {
    return this.polish(text, { ...options, style: 'formal' })
  }

  async changeTone(text: string, tone: string, options: any = {}): Promise<string> {
    return this.polish(text, { ...options, tone })
  }

  // 基础执行方法（保持兼容性）
  private async executeAction(action: string, input: any): Promise<string> {
    // Ensure service is initialized
    if (!this.isInitialized) {
      await this.initialize()
    }

    if (!this.isConfigured()) {
      throw new Error('AI服务未配置，请在设置中配置API密钥')
    }

    // Build messages
    const messages = this.buildMessages(action, input)

    try {
      const response = await this.providerManager.generateResponse(
        messages,
        this.config.provider
      )

      return response.content.trim()
    } catch (error) {
      log.error(`AI action ${action} failed:`, error)
      throw new Error(`AI处理失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }

  private buildMessages(action: string, input: any): BaseMessage[] {
    const systemPrompts: Record<string, string> = {
      polish: "你是一个专业的写作助手，请润色以下文本，使其更加流畅、专业和优雅。保持原意不变，只优化表达方式、语法结构和用词选择。",
      expand: "请对以下文本进行扩写，添加更多细节、背景信息和深入分析，使内容更加丰富和完整。保持原文的核心观点和逻辑结构。",
      translate: "你是一个专业的翻译助手，请将以下文本准确翻译成{target_lang}，保持原文的语气、风格和专业性。",
      summarize: "请为以下文本生成一个简洁明了的摘要，突出主要观点和关键信息，长度控制在原文的20-30%左右。",
      continueWriting: "请基于以下上下文智能续写内容，保持风格一致、逻辑连贯，自然地延伸和发展现有内容。续写内容应该与上下文高度相关且有价值。"
    }

    const systemPrompt = systemPrompts[action] || "你是一个AI写作助手，请根据用户需求提供帮助。"
    let userPrompt = ""

    switch (action) {
      case 'translate':
        userPrompt = systemPrompt.replace('{target_lang}', input.target_lang || 'English') + `\n\n请翻译以下文本：\n${input.text}`
        break
      case 'continueWriting':
        userPrompt = systemPrompt + `\n\n上下文：${input.context || '无特定上下文'}\n\n当前文本：${input.text}\n\n请续写：`
        break
      default:
        userPrompt = systemPrompt + `\n\n${input.text}`
        break
    }

    return [
      new SystemMessage(systemPrompt),
      new HumanMessage(userPrompt)
    ]
  }

  // 原有的其他方法保持不变
  private async getSecureApiKey(): Promise<string | null> {
    try {
      return await this.securityService.getApiKey(this.config.provider)
    } catch (error) {
      console.error(`Failed to get API key for ${this.config.provider}:`, error)
      return null
    }
  }

  public isConfigured(): boolean {
    try {
      const provider = this.providerManager.getProvider(this.config.provider)
      return !!provider && (!!this.config.apiKey || this.config.provider === 'local')
    } catch (error) {
      return false
    }
  }

  public getConfig(): EnhancedLangChainConfig {
    return { ...this.config }
  }

  public async testConnection(): Promise<boolean> {
    try {
      if (!this.isConfigured()) {
        return false
      }

      const result = await this.executeAction('polish', { text: 'Hello world' })
      return !!result
    } catch (error) {
      console.error('AI connection test failed:', error)
      return false
    }
  }

  // 获取服务统计信息
  public getServiceStats(): {
    isInitialized: boolean;
    langChainInitialized: boolean;
    memoryStats: any;
    projectStats: any;
    cacheStats: any;
  } {
    return {
      isInitialized: this.isInitialized,
      langChainInitialized: this.langChainInitialized,
      memoryStats: this.config.enableMemoryManagement ? this.memoryTool.getMemoryStats() : null,
      projectStats: this.config.enableProjectManagement ? { totalProjects: 0 } : null,
      cacheStats: this.cache.getStats(),
    }
  }

  // 获取可用的高级功能
  public getAvailableFeatures(): string[] {
    const features = ['polish', 'expand', 'translate', 'summarize', 'continueWriting']

    if (this.config.enableAdvancedFeatures) {
      features.push(
        'generateContent',
        'analyzeText',
        'formatMarkdown',
        'extractKeywords',
        'generateOutline',
        'improveSEO'
      )
    }

    if (this.config.enableMemoryManagement) {
      features.push('memoryManagement')
    }

    if (this.config.enableProjectManagement) {
      features.push('projectManagement')
    }

    return features
  }

  // 获取工具实例（用于高级用户）
  public getTextGenerationTool(): TextGenerationTool {
    return this.textGenerationTool
  }

  public getTextAnalysisTool(): TextAnalysisTool {
    return this.textAnalysisTool
  }

  public getMemoryTool(): MemoryManagementTool {
    return this.memoryTool
  }

  public getProjectTool(): ProjectManagementTool {
    return this.projectTool
  }
}

// 导出增强的服务
export { EnhancedLangChainService as LangChainService }
export default EnhancedLangChainService